﻿#include "MLPreviewRender.h"

MLPreviewRender::MLPreviewRender(
	const std::string output_path,
	double frame_rate,
	int frame_size_x,
	int frame_size_y,
	double target_secs,
	double particles_lifespan_max
) {
	_output_path = output_path;
	_target_frame_count = rint(frame_rate * target_secs);
	_start_frame_count = std::max<int>((int)(_target_frame_count - rint(frame_rate * particles_lifespan_max * 2)), 0);
	_frame_size_x = frame_size_x;
	_frame_size_y = frame_size_y;
}

void MLPreviewRender::render(std::vector<MLObj*>& objects, int particles_location) {
	printf("正在绘制粒子……\n");
	MLProgressbar progressbar(_target_frame_count - _start_frame_count, "粒子绘制进度");
	MLFrame void_frame(_frame_size_x, _frame_size_y);
	for (int i = _start_frame_count; i < _target_frame_count; i++) {
		objects[particles_location]->get_frame(i, void_frame);
		progressbar.update();
	}
	printf("正在生成预览图……\n");
	MLFrame ml_frame(_frame_size_x, _frame_size_y);
	FrameWriter writer = Utils::initFrameWriter(_frame_size_x, _frame_size_y);
	for (auto& obj : objects) {
		obj->get_frame((size_t)_target_frame_count, ml_frame);
	}
	uint8_t* frame = ml_frame.getFrame(writer);
	cv::Mat frame_mat = cv::Mat(cv::Size(_frame_size_x, _frame_size_y), CV_8UC3, frame);
	cv::cvtColor(frame_mat, frame_mat, cv::COLOR_RGB2BGR);
	cv::imwrite(_output_path, frame_mat);
	delete frame;
}